package antmongo

import (
	"EsTag/slog"
	"fmt"
	//	"os"
	//	"strconv"

	"github.com/astaxie/beego"

	//	_t "antServer/tools"

	"gopkg.in/mgo.v2"
)

var log = slog.Slog
var (
	session   *mgo.Session
	dburl     string
	dbname    string
	poolLimit int
)

// MgoLoadConfig 读取配置文件,初始化mongodb连接配置参数
func MgoLoadConfig() {
	dburl = beego.AppConfig.String("mongodb::url")
	if dburl == "" {
		dburl = "mongodb://ant:AntGolang2016@123.56.3.135:27017,101.200.45.172:27017,123.56.24.113:27017/antauth"
	}
	dbname = beego.AppConfig.String("mongodb::dbName")
	if dbname == "" {
		dbname = "ant"
	}
	var err error
	poolLimit, err = beego.AppConfig.Int("mongodb::poolLimit")
	if err != nil {
		poolLimit = 100
	}
	fmt.Println("dburl   " + dburl)
	fmt.Println("dbname   " + dbname)
	fmt.Println(poolLimit)
}

// GetSession 获取Mongodb的session，如果为空则重新创建，否则返回原有值
func GetSession() (*mgo.Session, error) {
	if session == nil {
		var err error
		session, err = mgo.Dial(dburl)
		if err != nil {
			log.Errorf("连接mongodb错误:%s", err.Error())
			return nil, err
		}
		session.SetPoolLimit(poolLimit)
	}
	return session.Clone(), nil
}

// GetSrcSession 获取源session
func GetSrcSession() *mgo.Session {
	if session == nil {
		var err error
		session, err = mgo.Dial(dburl)
		if err != nil {
			log.Errorf("连接mongodb错误:%s", err.Error())
			return nil
		}
		session.SetPoolLimit(poolLimit)
	}
	return session
}

// MgoInitSession 初始化
func MgoInitSession(sess *mgo.Session) {
	session = sess
}

// GetDB 获取指定的数据库名称
func GetDB() string {
	return dbname
}

// OPC 定义执行Mongodb操作的函数操作完成后关闭session
// 传入collection的名字和操作函数即可
func OPC(collection string, f func(*mgo.Collection)) {
	session, err := GetSession()
	if err != nil {
		log.Errorf("获取mongodb连接错误:%s", err.Error())
	}
	defer func() {
		session.Close()
		if err := recover(); err != nil {
			log.Errorf("执行mongodb操作错误:%s", err)
		}
	}()
	c := session.DB(dbname).C(collection)
	f(c)
}

// OPDC 定义执行Mongodb操作的函数操作完成后关闭session
// 传入数据库名字和collection的名字，外加操作函数即可
func OPDC(newdb string, collection string, f func(*mgo.Collection)) {
	session, err := GetSession()
	if err != nil {
		log.Errorf("获取mongodb连接错误:%s", err.Error())
	}
	defer func() {
		session.Close()
		if err := recover(); err != nil {
			log.Errorf("执行mongodb操作错误:%s", err)
		}
	}()
	c := session.DB(newdb).C(collection)
	f(c)
}
